const express = require('express')
const {expressjwt} = require('express-jwt')
const userRouter = require('./route/user.js')
const manageCenterRouter = require('./route/manageCenter.js')
const myCourseRouter = require('./route/myCourse')
const Message = require('./util/Message.js')
const swaggerUI = require('swagger-ui-express')
const openapi = require('./util/openapi.json')

const cors = require('cors')
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express()


const httpServer = createServer(app);
app.use(cors())
const io = new Server(httpServer, {
    cors: {
        origin: ["http://localhost:8080"],
        allowedHeaders: ["my-custom-header"],
        credentials: true
    }
})
io.on("connection", (socket) => {
    console.log(`用户 ${socket.id} 已上线 `);
    socket.on('message', item => {
        io.emit('allMsg', item)
    })

    socket.on("emit-private", e => {
        socket.to(e.socket_id).emit("echo-private", e);
    });

    socket.on("emit-join-public", e => {
        socket.join(e.room_id);
    });

    socket.on("emit-public", e => {
        socket.to(e.socket_id).emit("echo-public", e);
    });

    socket.on("disconnect", () => {
        console.log('断连', socket.id);
    });
});

app.use(express.static('public'))
app.use('/swagger.html', swaggerUI.serve, swaggerUI.setup(openapi))
app.use(expressjwt({
    secret: '...',
    algorithms: ['HS256']
}).unless({
    path: ['/user/login', '/user/signUp', '/user/test', '/user/upload', '/manage-center/getSubjectAndClass', '/manage-center/getSubject']
}))
app.use(express.json())
app.use('/user', userRouter)
app.use('/manage-center', manageCenterRouter)
app.use('/my-course', myCourseRouter)
app.use((err, req, res, next) => {
    /*
    * 这里是参数中没有携带 token 才进来的
    * 注意，不要删除上面形参中的 next，因为它就是根据形参个数来确定是否是错误处理中间件的
    * */
    const {status} = err
    // 搞不明白的时候记得打开下面的注释，这样控制台会有输出
    // console.log(err);
    if (status === 401) res.send(Message.sendFail())
})
// app.listen(3000, () => {
//     console.log('3000 端口已启动')
// })
httpServer.listen(3000, () => {
    console.log('3000 端口已启动')
})
